
/* 
    1 更改v4l2config初始化配置文件;
    2 使用新的config.c文件 获取mipi grey数据
    3 使用mpp_buffer的api获取buf的 *ptr len，然后写入文件 
*/
#include "v4l2config.h"
#include <stdio.h>
#include <stdlib.h>

#include "mpp_buffer.h"
#define FRAME_COUNT 100  // 捕获帧数
#define RAW_FILE_NAME "capture.raw"  // 输出文件名

int main() {
    CamSource *cam = NULL;
    FILE *raw_file = NULL;
    int frame_idx = -1;
    MppBuffer buf = NULL;
    uint8_t *data = NULL;
    size_t data_size = 0;
    int i = 0;
    printf("start get capture\n");
    // 初始化摄像头
    cam = camera_source_init("/dev/video0", 4, 768, 512, MPP_FMT_YUV400);
    if (!cam) {
        fprintf(stderr, "Camera initialization failed\n");
        return -1;
    }
    
    // 打开RAW文件
    raw_file = fopen(RAW_FILE_NAME, "wb");
    if (!raw_file) {
        fprintf(stderr, "Failed to open raw file: %s\n", RAW_FILE_NAME);
        camera_source_deinit(cam);
        return -1;
    }
    // 捕获并保存帧数据
    for (i = 0; i < FRAME_COUNT; i++) 
    {
        // 获取帧索引
        frame_idx = camera_source_get_frame(cam);
        if (frame_idx < 0) {
            fprintf(stderr, "Failed to get frame %d\n", i + 1);
            break;
        }
        // 获取缓冲区
        buf = camera_frame_to_buf(cam, frame_idx);
        if (!buf) {
            fprintf(stderr, "Failed to get buffer for frame %d\n", i + 1);
            camera_source_put_frame(cam, frame_idx);  // 放回缓冲区
            continue;
        }
        // 从缓冲区拿数据到文件
        size_t len = mpp_buffer_get_size(buf);
        void *data = mpp_buffer_get_ptr(buf);
        if (data && len > 0) {
            size_t written = fwrite(data, 1, len, raw_file);
            if (written != len) {
                fprintf(stderr, "Warning: Only wrote %zu of %zu bytes for frame %d\n", written, len, i + 1);
            } else {
                printf("Saved frame %d to RAW (size: %zu bytes)\n", i + 1, len);
            }
        } else {
            fprintf(stderr, "Invalid buffer data for frame %d\n", i + 1);
        }
        printf("Saved frame %d (size: %zu bytes)\n", i + 1, len);

        // 释放缓冲区，放回队列
        camera_source_put_frame(cam, frame_idx);
    }

    // 清理资源
    fclose(raw_file);
    camera_source_deinit(cam);
    printf("RAW data saved to %s\n", RAW_FILE_NAME);

    return 0;
}